<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>特种小分队</title>
    <style>
        :root {
            --bg-color: #f5f5f5;
            --text-color: #333;
            --message-bg: white;
            --avatar-bg: #e0e0e0;
            --code-bg: #f6f8fa;
            --code-border: #d0d7de;
            --code-header-bg: #eaeef2;
            --code-header-hover: #d8e0e7;
            --blockquote-border: #dfe2e5;
            --blockquote-color: #6a737d;
            --table-border: #dfe2e5;
            --table-header-bg: #f6f8fa;
        }

        @media (prefers-color-scheme: dark) {
            :root {
                --bg-color: #1a1a1a;
                --text-color: #e0e0e0;
                --message-bg: #2d2d2d;
                --avatar-bg: #404040;
                --code-bg: #2d2d2d;
                --code-border: #404040;
                --code-header-bg: #363636;
                --code-header-hover: #404040;
                --blockquote-border: #404040;
                --blockquote-color: #a0a0a0;
                --table-border: #404040;
                --table-header-bg: #363636;
            }
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", "Liberation Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
            margin: 0;
            padding: 0;
            background-color: var(--bg-color);
            color: var(--text-color);
            height: 100vh;
            overflow: hidden;
        }
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow-y: auto;
            padding: 10px;
            box-sizing: border-box;
        }
        .message {
            display: flex;
            margin-bottom: 15px;
        }
        .avatar {
            font-size: 24px;
            margin-right: 10px;
            width: 40px;
            height: 40px;
            background-color: var(--avatar-bg);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        .message-content {
            background-color: var(--message-bg);
            border-radius: 10px;
            padding: 10px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
            max-width: 80%;
        }
        .user-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .markdown-body {
            line-height: 1.5;
        }
        pre {
            background-color: var(--code-bg);
            border-radius: 3px;
            padding: 10px;
            overflow-x: auto;
        }
        code {
            font-family: 'Courier New', Courier, monospace;
            padding: 2px 4px;
            background-color: var(--code-bg);
            border-radius: 3px;
        }
        pre code {
            padding: 0;
            background-color: transparent;
        }
        blockquote {
            border-left: 4px solid var(--blockquote-border);
            margin-left: 0;
            padding-left: 10px;
            color: var(--blockquote-color);
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin: 10px 0;
        }
        table, th, td {
            border: 1px solid var(--table-border);
            padding: 6px 13px;
        }
        th {
            background-color: var(--table-header-bg);
        }
        
        /* 代码高亮样式 */
        @media (prefers-color-scheme: light) {
            .hljs-keyword { color: #d73a49; }
            .hljs-string { color: #032f62; }
            .hljs-number { color: #005cc5; }
            .hljs-function { color: #6f42c1; }
            .hljs-comment { color: #6a737d; }
            .hljs-variable { color: #e36209; }
        }
        
        @media (prefers-color-scheme: dark) {
            .hljs-keyword { color: #ff7b72; }
            .hljs-string { color: #a5d6ff; }
            .hljs-number { color: #79c0ff; }
            .hljs-function { color: #d2a8ff; }
            .hljs-comment { color: #8b949e; }
            .hljs-variable { color: #ffa657; }
        }
        
        img {
            max-width: 100%;
            height: auto;
            display: block;
        }
        
        .code-wrapper {
            margin: 12px 0;
            border: 1px solid var(--code-border);
            border-radius: 6px;
            background-color: var(--code-bg);
            overflow: hidden;
        }

        .code-wrapper summary {
            list-style: none;
            cursor: pointer;
            padding: 8px 16px;
            background-color: var(--code-header-bg);
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 14px;
            border-bottom: 1px solid var(--code-border);
            transition: background-color 0.2s ease;
        }

        .code-wrapper summary:hover {
            background-color: var(--code-header-hover);
        }

        .code-wrapper summary::marker {
            display: none;
        }

        .code-wrapper[open] summary::after {
            content: "▲ 隐藏代码";
            font-size: 12px;
            color: var(--blockquote-color);
        }

        .code-wrapper summary::after {
            content: "▼ 查看代码";
            font-size: 12px;
            color: var(--blockquote-color);
        }

        .code-wrapper pre {
            margin: 0;
            border: none;
            border-radius: 0;
        }
        
        .copy-button:hover {
            background-color: var(--code-header-hover);
        }
    </style>
    <script src="js/marked.min.js"></script>
    <script src="js/highlight.min.js"></script>
    <script src="js/purify.min.js"></script>
    <!-- 根据系统主题动态加载代码高亮主题 -->
    <script>
        // 检测系统主题并加载对应的代码高亮主题
        function loadHighlightTheme() {
            const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
            const themeLink = document.createElement('link');
            themeLink.rel = 'stylesheet';
            themeLink.href = isDarkMode 
                ? 'css/github-dark.min.css'
                : 'css/github.min.css';
            document.head.appendChild(themeLink);
        }
        
        // 监听系统主题变化
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', loadHighlightTheme);
        
        // 初始加载主题
        document.addEventListener('DOMContentLoaded', loadHighlightTheme);
    </script>
    <script>
        const renderer = new marked.Renderer();
        // 把非代码块里的 HTML（如 <title>）转义成文本
        renderer.html = function(html) {
        return html
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
        };

        // 设置 marked 选项
        marked.setOptions({
            renderer,
            highlight: function(code, language) {
                if (language && hljs.getLanguage(language)) {
                    return hljs.highlight(code, {language: language}).value;
                }
                return hljs.highlightAuto(code).value;
            },
            gfm: true,
            breaks: true
        });
        
        // 跟踪最后发送消息的用户
        let lastUser = '';
        let lastMessage = null;
        let lastRawContent = ''; // 存储上一条原始的 markdown 文本
        
        // 追踪是否用户正在滚动查看历史消息
        let userScrolling = false;
        let scrollTimeout = null;
 
        function wrapCodeBlocks() {
            const codeBlocks = document.querySelectorAll('pre:not(.wrapped)');

            codeBlocks.forEach(pre => {
                // 标记这个代码块已经被包装过
                pre.classList.add('wrapped');
                
                const wrapper = document.createElement('details');
                wrapper.className = 'code-wrapper';
                
                // 获取代码语言
                const codeElement = pre.querySelector('code');
                const language = codeElement ? codeElement.className.replace('language-', '') : 'text';
                
                const summary = document.createElement('summary');
                summary.textContent = `点击展开代码 (${language})`;
                
                // 添加复制按钮
                const copyButton = document.createElement('button');
                copyButton.className = 'copy-button';
                copyButton.textContent = '复制';
                copyButton.onclick = function(e) {
                    e.stopPropagation();
                    const code = pre.textContent;
                    navigator.clipboard.writeText(code).then(() => {
                        copyButton.textContent = '已复制!';
                        setTimeout(() => {
                            copyButton.textContent = '复制';
                        }, 2000);
                    });
                };
                
                pre.parentNode.insertBefore(wrapper, pre);
                wrapper.appendChild(summary);
                wrapper.appendChild(copyButton);
                wrapper.appendChild(pre);
            });
        }

        function appendMessage(avatar, user, msg) {
            const chatContainer = document.querySelector('.chat-container');
            
            // 检查是否是同一用户连续发消息
            if (user === lastUser && lastMessage) {
                // 获取最后一条消息的内容区域
                const markdownDiv = lastMessage.querySelector('.markdown-body');
                
                // 拼接原始的 markdown 文本，添加换行符确保格式正确
                lastRawContent += '\n' + msg;
                
                // 使用 marked 解析 markdown，这里不再使用 DOMParser
                try {
                    // 安全地将 markdown 转换为 HTML
                    markdownDiv.innerHTML = DOMPurify.sanitize(marked.parse(lastRawContent));
                } catch(e) {
                    console.error("解析错误:", e);
                    // 如果解析失败，至少显示纯文本
                    markdownDiv.textContent = lastRawContent;
                }
            } else {
                // 创建新的消息元素
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message';
                messageDiv.setAttribute('data-user', user);
                
                // 创建头像元素
                const avatarDiv = document.createElement('div');
                avatarDiv.className = 'avatar';
                avatarDiv.textContent = avatar;
                
                // 创建消息内容容器
                const contentDiv = document.createElement('div');
                contentDiv.className = 'message-content';
                
                // 创建用户名元素
                const userNameDiv = document.createElement('div');
                userNameDiv.className = 'user-name';
                userNameDiv.textContent = user;
                
                // 创建消息内容元素
                const markdownDiv = document.createElement('div');
                markdownDiv.className = 'markdown-body';
                
                // 使用 marked 解析 Markdown
                try {
                    // 安全地将 markdown 转换为 HTML
                    markdownDiv.innerHTML = DOMPurify.sanitize(marked.parse(msg));
                } catch(e) {
                    console.error("解析错误:", e);
                    // 如果解析失败，至少显示纯文本
                    markdownDiv.textContent = msg;
                }
                
                // 存储该消息的原始 markdown 文本
                lastRawContent = msg;
                
                // 存储最后的消息对象引用
                lastMessage = messageDiv;
                
                // 组装消息
                contentDiv.appendChild(userNameDiv);
                contentDiv.appendChild(markdownDiv);
                messageDiv.appendChild(avatarDiv);
                messageDiv.appendChild(contentDiv);
                
                // 添加到聊天容器
                chatContainer.appendChild(messageDiv);
            }
            
            // 更新最后发送消息的用户
            lastUser = user;
            
            // 如果用户没有主动滚动查看历史，则自动滚动到底部
            if (!userScrolling) {
                scrollToBottom();
            }
            wrapCodeBlocks();
        }
        
        // 滚动到底部的函数
        function scrollToBottom() {
            const chatContainer = document.querySelector('.chat-container');
            setTimeout(() => {
                chatContainer.scrollTop = chatContainer.scrollHeight;
            }, 10);
        }
        
        // 在文档加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            const chatContainer = document.querySelector('.chat-container');
            
            // 监听滚动事件以检测用户是否正在查看历史消息
            chatContainer.addEventListener('scroll', function() {
                clearTimeout(scrollTimeout);
                userScrolling = true;
                
                // 距离底部小于 50px 时认为用户已经看到最新消息
                const isAtBottom = chatContainer.scrollHeight - chatContainer.scrollTop - chatContainer.clientHeight < 50;
                
                // 如果滚动到底部或接近底部，重置 userScrolling 标志
                if (isAtBottom) {
                    userScrolling = false;
                }
                
                // 如果用户 3 秒不滚动，假设他们已经看完了想看的历史消息
                scrollTimeout = setTimeout(() => {
                    if (isAtBottom) {
                        userScrolling = false;
                    }
                }, 3000);
            });
        });
    </script>
</head>
<body>
    <div class="chat-container"></div>
</body>
</html>
